package com.rfsp.common.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;

import java.io.UnsupportedEncodingException;
import java.util.*;

public class JsonUtil {
    public static ObjectMapper mapper;
    public static ObjectWriter writer ;
    public static ObjectReader reader;
    static {
        mapper = new ObjectMapper();
    	mapper.setTimeZone(TimeZone.getDefault());
        mapper.setDateFormat(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        //mapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
        writer = mapper.writerWithDefaultPrettyPrinter();
        reader = mapper.readerForMapOf(Object.class);
    }
	

	public static <T> String toJson(T obj) throws JsonProcessingException {
		return writer.writeValueAsString(obj);
	}

    public static <T> String toJson(Map<String, T> map) throws Exception {
        return writer.writeValueAsString(map);
    }

    public static <T> T toBean(String json, Class<T> clazz) throws JsonProcessingException {
        return mapper.readValue(json, clazz);
    }

	/**
	 *将json串转换为map对象，包含嵌套情况（json串中含有list等情况）
	 * @param json
	 * @return
	 * @throws JsonProcessingException 
	 * @throws JsonMappingException 
	 */
	public static Map<String, Object> toMap(String json) throws JsonMappingException, JsonProcessingException  {
        JsonNode rootNode = reader.readTree(json);
        Map<String,Object> map = new HashMap<>();
        Iterator<String> fieldNames = rootNode.fieldNames();
        while(fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            JsonNode node = rootNode.get(fieldName);
            if(node.isValueNode()) {
                map.put(fieldName, node.asText());
            } else if (node.isObject()) {
                map.put(fieldName, toMap(node.toString()));
            } else if (node.isArray() && !node.isEmpty()) {
            	Iterator<JsonNode> elements = node.elements();
                while (elements.hasNext()) {
                    JsonNode jn = elements.next();
                    toMap(jn.toString());
                }
            }
        }
		return map;
	}
	
	
	/**
	 *将json串转换为map对象，包含嵌套情况（json串中含有list等情况）
	 * @param json
	 * @return
	 * @throws JsonProcessingException 
	 * @throws JsonMappingException 
	 */
	public static Map<String, Object> toMap2(String json) throws JsonMappingException, JsonProcessingException  {
        JsonNode rootNode = reader.readTree(json);
        Map<String,Object> map = new HashMap<>();
        Iterator<String> fieldNames = rootNode.fieldNames();
        while(fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            JsonNode node = rootNode.get(fieldName);
            if(node.isValueNode()) {
                map.put(fieldName, node.asText());
            } else if (node.isObject()) {
                map.put(fieldName, toMap2(node.toString()));
            } else if (node.isArray() && !node.isEmpty()) {
            	Iterator<JsonNode> elements = node.elements();
            	
            	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                while (elements.hasNext()) {
                    JsonNode jn = elements.next();
                    list.add(toMap2(jn.toString()));
                }
                
                map.put(fieldName, list);
            }
        }
		return map;
	}
	

    public static <T> List<T> toBeanList(String json, Class<T> clazz, String namesNode) throws JsonProcessingException {
        String jsonList = null;
        JsonNode rootNode = mapper.readTree(json);
        if(namesNode!=null){
            JsonNode parentNode = rootNode.get("data");//获取外层data父节点
            JsonNode childNode = parentNode.get(namesNode);//获取子节点
            jsonList = childNode.toString();
        }else{
            jsonList = rootNode.toString();
        }

        //T jb = objectMapper.readValue(jsonList, clazz);

        return mapper.readValue(jsonList, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
    }

    /**
     * 判断json是否为空值
     * @param json
     * @return
     */
    public static boolean isEmptyJson(String json) throws JsonParseException {
        boolean isEmptyJson = true;
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(json);

            if (jsonNode.isObject() && jsonNode.size() == 0) {
                isEmptyJson = true;
            } else {
                isEmptyJson = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new JsonParseException(e.getMessage());
        }
        return isEmptyJson;
    }

}
